function plotdatafile = TFC3_CreateAveragedData
%TFC3_CREATEAVERAGEDDATA Load all datafiles, derive data that needs to be
%plotted, and save that into a big plotfile

global Database;

%% Set up environment
cFilename = strcmp(Database.tfc_header, 'Filename');
cSubjects = strcmp(Database.tfc_header, 'Subjects');
cConditions = strcmp(Database.tfc_header, 'Conditions');
cFrequencyBins = strcmp(Database.tfc_header, 'FrequencyBins');
cBaselineSettings = strcmp(Database.tfc_header, 'BaselineSettings');
cTimes = strcmp(Database.tfc_header, 'Times');

for row = 1:size(Database.tfc,1)
    if row == 1
        frequencyBins = Database.tfc{row,cFrequencyBins};
        baselineSettings = Database.tfc{row,cBaselineSettings};
        times = Database.tfc{row,cTimes};
    else
        % Check to see if the frequencybins, baselinesettings and times are
        % all the same...
        warning('Frequencybins, baselinesettings and times are not checked.');
    end

    TFCDATA = load(Database.tfc{row,cFilename}, '-mat');
    
    for sIdx = fieldnames(TFCDATA.data)'
        subject = sIdx{1};
        for chIdx = fieldnames(TFCDATA.data.(subject))'
            channel = chIdx{1};
            for coIdx = fieldnames(TFCDATA.data.(subject).(channel))'
                condition = coIdx{1};

                disp(['Adding average: ' subject '/' channel '/' condition]);
                data.(subject).(channel).(condition).meanpower = mean(TFCDATA.data.(subject).(channel).(condition).power, 3);
                data.(subject).(channel).(condition).ttest = TFCDATA.data.(subject).(channel).(condition).ttest;

            end
        end
    end
    
    
end

plotdatafile = [Database.Path.TFCData 'All tfcdata.mat'];
save(plotdatafile, 'data', 'frequencyBins', 'times',  'baselineSettings', '-v7.3');
end

